package com.qf.ssm.websocket;

import com.qf.ssm.event.CheckDeviceStatusEvent;
import com.qf.ssm.event.UpdateDevicesStatusEvent;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Map;

public interface BaseCheckStatusHandler {

    //钩子方法,因为在我们当前的接口中没有数据,需要数据,那么需要子类重写这些方法返回数据,供接口使用
    ApplicationContext getContext();
    Map<Object, WebSocketSession> getAllClients();

    @EventListener
    @Async
    default void onEvent(CheckDeviceStatusEvent event) {
        //检查设备状态就是遍历所有的在线设备,看看谁不在,
        //怎么知道谁不在,发送一个消息,出现异常就说明不在了

        getAllClients().forEach((uuid, session) -> {

            try {
                session.sendMessage(new TextMessage(""));
            } catch (Exception e) {
                e.printStackTrace();

                System.err.println("设备编号为" + uuid + "已经离线了");
                getContext().publishEvent(new UpdateDevicesStatusEvent((String) uuid, "0"));
                getAllClients().remove(uuid);
            }

        });
    }
}
